<template>
 <view class="box_body">

    <scroll-view scroll-x="true" class="left">
        <view style="display: flex;">
            <view class="row" :class="[0 === showCategoryIndex ? 'on' : '']" @tap="showCategory(0)">
                <view class="text" style="display: flex;">
                    <!-- <view class="block" :class="'bg-'+themeColor.name"></view> -->
                    预约服务
                </view>
            </view>
            <view class="row" :class="[1 === showCategoryIndex ? 'on' : '']" @tap="showCategory(1)">
                <view class="text" style="display: flex;">
                    <!-- <view class="block" :class="'bg-'+themeColor.name"></view> -->
                    预约服务人
                </view>
            </view>

        </view>
    </scroll-view>
	<!-- 选择日期插件 -->
    <DateTabs :value.sync="value1" color="#fca119" @change='onDateTabsChange' ></DateTabs>
	<view class="zhanwei"></view>
	 <view v-if="0 === showCategoryIndex" class="box_body_left">
    
<!----------------------------- 套餐选择循环start------------------------- -->
	<view class="right">
		
		<view class="item" v-for="(item, index) in serverData" :key="item.id">
			<view class="item_top">

			<view class="item_left">
				<img :src="item.cover!=null?item.cover:'/static/zwpic.png'" alt="" />
			</view>
			<view class="item_right">
				<view class="item_type">
					<span>{{item.name}}</span>
				</view>
				<view class="item_time">
					<!-- <span>所选时间：</span><vvSelect class="vv-select" v-model="categoryCode[item.id]" placeholder="未选择" :list="categorys" valueKey='value' label="label" @change="changeSoltTime(item.id)"></vvSelect> -->
				<span>所选时间：</span> <time-selector class="time-selector" :backend-data="item" @time-selected="handleTimeSelected" :severId="item.id"></time-selector>
				</view>
				<view class="isOnline">
					面议
				</view>
			</view>
		</view>
	<view class="sub_zhanwei">
			<view class="item_submit" @click="left_submit(item.id)">预约</view>
	</view>
		</view>
		
	</view>
	
<!-- 套餐选择循环end -->
 </view>
 <!-- 预约服务人页面 -->
    <view v-if="1 === showCategoryIndex" class="box_body_right">
		<view class="zhanwei"></view>
		<view class="rItem" v-for="(item, index) in allCameraInfo" :key="item.id">
			<img :src="item.userImage?item.userImage:'https://gzg123.cn/uploads/allimg/20221031/1-22103115510HP.jpg'" alt="" />
			<view class="rItem_person">
				<span class="rItem_name">{{item.name}}</span>
				<span><uni-rate :readonly="true" :value="item.grade/2.0" size="18" allow-half/></span>
			</view>
			<view class="item_submit rItem_submit"  @click="showModal(item.username)">预约</view>
		</view>	
				
    </view>
	<uni-popup ref="popup" type="center">
      <view class="modal-content">
        <view class="modal-title">预约信息</view>
        <view class="modal-input">
          <text>手机号:</text>
          <input v-model="selfcameraInfo.phone" placeholder="请输入手机号" />
        </view>
        <view class="modal-select">
          <text>选择时间段:</text>
          <picker @change="bindPickerChange" :value="index" :range="timeOptions">
            <view class="picker">
              {{ timeOptions[index] }}
            </view>
          </picker>
        </view>
        <button @click="saveAndClose">确认预约</button>
      </view>
    </uni-popup>
	
 </view>
</template>

<script>
import DateTabs from '@/uni_modules/hope-11-date-tabs/components/hope-11-date-tabs/date-tabs.vue'
import vvSelect from '@/components/vv-select/vv-select.vue'
import TimeSelector from '@/pages/category/seltTimeCom.vue';
// import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
import {getServerInfo,getCameraInfo,getUserInfo,reserve,reserveCamera} from '../../api/category.js'
export default {
  name: 'TsuniCategory',
  components: {
		   DateTabs,
		   vvSelect,
		   TimeSelector
		  },
  data() {
    return {
	serverData:[],//所有服务的信息
    showCategoryIndex:0,//一级菜单高亮显示序号
    value1:'',//当前日期时间
	selectTime:'',//用户选择的时间戳（天0时0分0秒）
	allCameraInfo:[],//所有摄影师的信息
	userInfo:{},//当前登录用户信息
	today:'',//用户打开app当天的日期
	cameraName:'',//当前用户选择的摄影师
	selfcameraInfo: {
        phone: '',
        time: 0
      },
	  timeOptions: ['8:00-10:00', '10:00-12:00', '14:00-16:00', '16:00-18:00'],//数组存储了可选的时间段
      index: 0,
	categoryCode: [],//用户选择的时间段，0代表8点-10点，1代表10点-12点，2代表14点-16点，3代表16点-18点
	categorys: [{
          label: '8：00-10：00',
          value: 0
        },{
          label: '10：00-12：00',
          value: 1
        },{
          label: '14：00-16：00',
          value: 2
        },{
          label: '16：00-18：00',
          value: 3
        }
	
	], // 类别list
	countTime:[1,7200,21600,28800],//计算秒级时间戳差，分别代表8点，10点，14点，16点
	serverId:'',//当前选中的服务id
	severTime:'',//当前选中的服务时间在数组中的顺序
    };
  },

  mounted() {
	
	// 获取当前用户信息
	this.getData2();
	// console.log(this.value1);
	console.log(this.selectTime);
	// console.log(this.allCameraInfo);
	
  },
  onTabItemTap() {
  		// 您点击了“导航”页...
  		// this.$store.state.cultureLimit=false;
  	},
  computed: {
    filteredTimeOptions(times) {
      return this.timeOptions.filter(time => {
        const [start, end] = time.split('-');
        const startTime = this.parseTime(start);
        const endTime = this.parseTime(end);
  
        // 判断时间段是否在不可选时间段列表中
        // if (this.unavailableTimes.includes(time)) {
        //   return false;
        // }
		let tmparr=times.map((item,index)=>{
			return !item?timeOptions[index]:''
		})
		if(tmparr.includes(time)){
			return false;
		}
  
        // 判断时间段的起始时间是否小于当前时间
		if (this.selectTime==this.today) {
			  if (startTime < this.currentTime) {
          return false;
        }
		}
      
        return true;
      });
    }
  },

  methods: {
	// 分类切换显示
    showCategory(index) {
			this.showCategoryIndex = index;
	},
	// 获取用户打开app当天的日期
	getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(now.getDate()).padStart(2, '0');
	  const date = new Date(`${year}-${month}-${day}`);
	  if (isNaN(date.getTime())) {
	    throw new Error('Invalid date string');
	  }
	  const timestamp = date.getTime() / 1000;
      this.today = timestamp;
    },
// 点击日期方法
    onDateTabsChange(e){
			    console.log(e,'adafds')
				console.log(this.value1)
				this.dateStringToTimestamp(this.value1)
				this.getData();
			},
	// 将yy-mm-dd事件转化成秒级时间戳
	dateStringToTimestamp(dateString) {
	  // 创建日期对象
	  const date = new Date(dateString);
	  
	  // 检查日期是否有效
	  if (isNaN(date.getTime())) {
	    throw new Error('Invalid date string');
	  }
	  
	  // 获取毫秒格式的时间戳并转换为秒格式
	  const timestamp = Math.floor(date.getTime() / 1000);
	  
	//   return timestamp;
	this.selectTime=timestamp;
	},
	async getData(){
		// 给后端传serData参数用于后端判断用户各个服务的时间段是否可选
		const serData={};
		serData.username=this.userInfo.username;
		serData.t=this.selectTime;
		console.log(this.selectTime);
		// 获取所有套餐服务信息
	const resData=await getServerInfo(serData);
	console.log(resData.data.data);
	this.serverData=resData.data.data;
		// 获取所有摄影师信息
	const allCameraInfo=await getCameraInfo();
	console.log(allCameraInfo);
	this.allCameraInfo=allCameraInfo.data.data;

	},
// 页面首次加载时获取当前用户信息
	async getData2 (){
	const userInfo=await getUserInfo(this.$store.state.username);
	 console.log(userInfo);
	 this.userInfo=userInfo.data.data;	
	this.dateStringToTimestamp(this.value1)
	this.getData();
		},
	// 根据套餐服务进行预约
	left_submit(serveId){
		let data={};
		data.username=this.userInfo.username;
		data.serverid=serveId;

		// 给用户选择的时间戳加上具体时间点的时间戳
		let  dianTime=this.countTime[this.severTime]
		console.log(dianTime);
		if (dianTime) {
			data.time=this.selectTime+dianTime;
			// 预约成功后清空时间
			this.categoryCode[serveId]='';
			this.categoryCode=[];
		reserve(data).then(res=>{

			console.log(res);
			const response=res.data;
			if(response.code===1){
                uni.showToast({
                    title:response.msg,
                    icon:'success'
                }) 
				this.getData2()       
            }else{
                uni.showToast({
                        title:response.msg,
                        icon:'error'
                    }) 
				this.getData2()   
            }
		}).catch(err=>{
			uni.showToast({
				title:'预约错误',
				icon:'error'
			})
		})
		}else{
			uni.showToast({
				title:'请选择时间段',
				icon:'none'
			})
		}
		
	},
	// 提交根据摄影师进行预约
	// 方法用于打开模态框
	showModal(caramreName) {
		this.cameraName=caramreName;
      this.$refs.popup.open();
    },
	// 方法用于处理时间段选择器的变化，并更新 selfcameraInfo 中的时间段。
    bindPickerChange(e) {
      this.index = e.target.value;
      this.selfcameraInfo.time = this.index;
    },
	// 方法用于保存数据并关闭模态框。
	saveAndClose() {
      // 保存数据
	  let data={};
      console.log('保存的数据:', this.selfcameraInfo);
	 if (this.validatePhoneNumber(this.selfcameraInfo.phone)) {
		data.username=this.userInfo.username;
		data.target=this.cameraName;
		data.phone=this.selfcameraInfo.phone;

		// 给用户选择的时间戳加上具体时间点的时间戳
		let  dianTime=this.countTime[this.selfcameraInfo.time];
		if (dianTime) {
			data.time=this.selectTime+dianTime;
		} 
			// 关闭模态框
			this.$refs.popup.close();
		reserveCamera(data).then(res=>{
			const response=res.data;
			if(response.code===1){
                uni.showToast({
                    title:response.msg,
                    icon:'success'
                })        
            }else{
                uni.showToast({
                        title:response.msg,
                        icon:'error'
                    })    
            }
		}).catch(err=>{
			uni.showToast({
					title:"预约失败",
					icon:'error'
				})	
		})
	
	 
	 }
      
    },
	validatePhoneNumber(e) {  
      // 简单的手机号验证，可以根据需要修改  
      const phone = e;  
      const regex = /^1[3-9]\d{9}$/;  
      if (!regex.test(phone)) {  
        uni.showToast({  
          title: '手机号格式不正确',  
          icon: 'none'  
        });  
		return 0;
      }else{
		return 1;
	  }
    },  
	// 判断所选时间段是否小于当前时间段
	parseTime(timeStr) {
	  const [hour, minute] = timeStr.split(':').map(Number);
	  const date = new Date(this.currentTime);
	  date.setHours(hour);
	  date.setMinutes(minute);
	  date.setSeconds(0);
	  date.setMilliseconds(0);
	  return date;
	},
	// 用户选择的时间段（TimeSelector组件的）
	handleTimeSelected(time,severId) {
	    // this.selectedTimes[itemId] = time;
	    // console.log(`Selected time for item  ${time}`);
		let index=this.timeOptions.indexOf(time);
		console.log(index,severId);
		this.severTime=index
	  }
	

  },
};
</script>

<style lang="scss">
		    .left,
			.right {
				// position: absolute;
				// top: 80upx;
				/*  #ifdef  APP-PLUS  */
				top: calc(80upx + var(--status-bar-height));
				/*  #endif  */
				// bottom: 0upx;
				display: flex;
			}

			.left {
				// width: 24%;
				// left: 0upx;
				background-color: $page-color-base;
				display: flex;

				.row {
					width: 100%;
					height: 90upx;
					display: flex;
					align-items: center;

					.text {
						width: 100%;
						position: relative;
						font-size: 28upx;
						display: flex;
						justify-content: center;
						color: #3c3c3c;

						.block {
							position: absolute;
							width: 0upx;
							left: 0;
						}
					}

					&.on {
						height: 100upx;
						background-color: #fff;

						.text {
							font-size: 30upx;
							font-weight: 600;
							color: #2d2d2d;

							.block {
								width: 6upx;
								height: 120%;
								left: 10upx;
							}
						}
					}
				}
			}

</style>
<style scoped>
	.right{
		display: flex;
		flex-direction: column;
	}
	.zhanwei{
		height: 30upx;
	}
	.item{
		width: 90%;
		display: flex;
		flex-direction: column;
		background-color: white;
		margin-left: 5%;
		border-radius: 10upx;
		margin-top: 30upx;
	/* 	padding-top: 10upx; */
		
	}
	.item_type{
		font-weight: 700;
		font-size: larger;
		margin-left: 10upx;
	}
	.item_time{
		font-size: 26upx;
		margin-left: 10upx;
		margin-top: 5upx;
		/* margin-bottom: 5upx; */
	}
	.isOnline{
		margin-left: 10upx;
		color: #fca119;
		font-size: large;
	}
	*{
		padding: 0;
		margin: 0;
	}
	.item_left img{
		width: 250upx;
		height: 180upx;
		border-radius: 5upx;
		
	}
	.item_right{
		border-bottom: 1upx solid black;
		width: 90%;
		height: 170upx;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}
	.item_top{
		width: 100%;
		display: flex;
		align-items: center;
		position: relative;
		align-content: space-around;
		
	}
	
	
	.item_submit{
		/* margin-top: 10upx; */
		width: 80upx;
		height: 50upx;
		line-height: 50upx;
		border-radius: 25upx;
		background-color: #fca119;
		color: white;
		font-size: 20upx;
		padding: 5upx;
		text-align: center;
		font-weight: 600;
		position: absolute;
		right: 10upx;
	}
	.sub_zhanwei{
		position: relative;
		width: 100%;
		height: 55upx;
	}
	
	/* 预约服务人样式部分 */
	
	.rItem{
		width: 90%;
		display: flex;
		flex-direction: row;
		background-color: white;
		margin-left: 5%;
		border-radius: 10upx;
		margin-top: 30upx;
		flex-wrap: nowrap;
		    justify-content: space-between;
		    align-items: center;
	}
	.rItem img{
		width: 170upx;
		height: 170upx;
		border-radius: 50%;
		
	}
	.rItem_name{
		font-weight: 700;
		font-size: large;
		margin-bottom: 10upx;
	}
	.rItem_person{
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	.rItem_submit{
		position: relative;
		width: 120upx;
		height: 75upx;
		line-height: 75upx;
		font-size: 30upx;
		
	}
	.vv-select{
		display: inline-block;
		text-align: left;
		padding: 10upx 0;
	}
	/* 模态框样式 */
	.modal-content {
  padding: 30upx;
  background-color: #fff;
  border-radius: 10upx;
  width: 80%;
  max-width: 600upx;
}

.modal-title {
  font-size: 23upx;
  margin-bottom: 20upx;
}

.modal-input,
.modal-select {
  margin-bottom: 15upx;
}

.modal-input text,
.modal-select text {
  display: block;
  margin-bottom: 5upx;
}

.picker {
  padding: 10upx;
  border: 1upx solid #ccc;
  border-radius: 5upx;
}
.time-selector{
	width: 200upx;
	display: inline;
}
</style>